import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { ListItemType } from '../../types'


interface CarStateType {
	loading: boolean
	car: CarItemType[]
}

interface CarItemType extends ListItemType {
	count: number
	isChecked: boolean
}


const initialState: CarStateType = {
	loading: false,
	car: []
}


const carSlice = createSlice({
	name: 'car',
	initialState,
	reducers: {
		addCar(state, action: PayloadAction<ListItemType>) {
			const product = state.car.find(v => v.id === action.payload.id);
			if (product) product.count++  // 存在数量+
			else state.car.push({ ...action.payload, count: 1, isChecked: false })  // 不存在添加新数据
		},
		addCarCount(state, action: PayloadAction<CarItemType>) {
			const item = state.car.find(v => v.id === action.payload.id)
			if(item) item.count++
		},
		subCarCount(state, action: PayloadAction<CarItemType>) {
			const item = state.car.find(v => v.id === action.payload.id)
			if(item) item.count--
		},
		switchCarCheck(state, action: PayloadAction<CarItemType>) {
			const item = state.car.find(v => v.id === action.payload.id)
			if(item) item.isChecked = !item.isChecked
		},
		modifyAllCarCheck(state, action: PayloadAction<boolean>) {
			state.car.forEach(v => v.isChecked = action.payload)
		}
	}
})

export const { addCar, addCarCount, subCarCount, switchCarCheck, modifyAllCarCheck } = carSlice.actions
export default carSlice